<template>
  <div id="app">
    <div class="con">
         <el-item v-for="(item,index) in list" :key="index"
         :src="item.src" :tit="item.tit" :msg="item.msg" :id="item.id" :price="item.price" :num="item.num"></el-item>
         <div>数量：{{nums}}总价：{{sums}}</div>
    </div>
     
  </div>
</template>

<script>
import elItem from "./components/el.vue"
export default {
  data(){
    return {
      list:[],
      buy:[],
    }
  },
  created(){
    this.getData();
    this.$bus.$on('add',(id,num)=>{
      let index=this.list.findIndex(item=>item.id===id);
      let isBuy=this.buy.findIndex(bitem=>bitem===id)
      this.list[index].num=num
      if(isBuy==-1){
        this.buy.push(this.list[index])
      }
    
    })
  },
  computed:{
    nums(){
      return this.buy.reduce((pre,cur)=>{
        return pre+cur.num
      },0)
    },
    sums(){
       return this.buy.reduce((pre,cur)=>{
        return pre+cur.price*cur.num
      },0)
    }
  },
  methods:{
    getData(){
      this.$http("/api/list").then((res)=>{
       if(res.data.code==1){
         let data=res.data.data;
         data.map((item)=>{
           item.num=0;
           return item
         })
         this.list=data;
       }
      }).catch((erro)=>{
        console.log(erro)
      })
    }
  },
  components:{
    elItem
  }
  
}
</script>

<style>
@import "./assets/common.css"
</style>
